<?php

class Application_Model_User extends Engine_Model_Abstract
{
  public function __construct($user_id = null)
  {
    parent::__construct(new Application_Model_DbTable_Users, $user_id);
  }
  public function getIdentity()
  {
    return $this->user_id;
  }

  public function getType()
  {
    return 'user';
  }

  public function getProfilePhoto($type = '')
  {
    $filesTable = new Application_Model_DbTable_Storages();
    $select = $filesTable->select()
      ->where('user_id = ?', $this->getIdentity())
      ->where('type = ?', $type)
      ->where('name = ?', 'profile')
      ->limit(1);
    $file = $filesTable->fetchRow($select);
    return '<img src="'. $file['storage_path'] .'" />' ;
  }

  public function getDisplayName()
  {
    $display_name = $this->first_name . " " . $this->last_name;

//    if (mb_strlen($display_name, 'utf-8') > 20 ) {
//      $display_name = mb_substr($display_name, 0, 17, 'utf-8') . "...";
//    }
    return $display_name;
  }


  public function getRole()
  {
    return ucfirst($this->role);
  }

  public function getGender()
  {
    return ucfirst($this->gender);
  }

  public function getCreationDate()
  {
    return date("Y-m-d", strtotime($this->creation_date));
  }

  public function save()
  {
    $this->last_login_ip = $_SERVER['REMOTE_ADDR'];
    $this->last_login_date = date("Y-m-d H:i:s");
    $this->modified_date = date("Y-m-d H:i:s");
    parent::save();
  }

  public function authorize($email, $password) {
    $auth = Zend_Auth::getInstance();
    $authAdapter = new Zend_Auth_Adapter_DbTable(
      $this->_dbTable->getDefaultAdapter(),
      'users',
      'email',
      'password',
      'md5(?)'
    );
    $authAdapter->setIdentity($email)
      ->setCredential($password);

    $result = $auth->authenticate($authAdapter);
    if ($result->isValid()) {
      $storege = $auth->getStorage();
      $storege->write($authAdapter->getResultRowObject(null, array('password')));
      return true;
    } else {
      return false;
    }
  }

  public function setPhoto($photo)
  {
    $file = '';
    $fileName = '';
    if( $photo instanceof Zend_Form_Element_File ) {
      $file = $photo->getFileName();
      $fileName = $file;
    } else if( is_array($photo) && !empty($photo['tmp_name']) ) {
      $file = $photo['tmp_name'];
      $fileName = $photo['name'];
    }

    if( !$fileName ) {
      $fileName = $file;
    }

    $extension = ltrim(strrchr(basename($fileName), '.'), '.');
    $base = 'profile'/*rtrim(substr(basename($fileName), 0, strrpos(basename($fileName), '.')), '.')*/;
    $path = PUBLIC_PATH . DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . 'users' . DIRECTORY_SEPARATOR . Zend_Auth::getInstance()->getIdentity()->user_id;
    $params = array(
      'parent_type' => $this->getType(),
      'parent_id' => $this->getIdentity(),
      'user_id' => $this->getIdentity(),
      'name' => $base,
      'extension' => $extension,
    );
    @mkdir($path, 0777, true);
    // Resize image (main)
    $mainPath = $path . DIRECTORY_SEPARATOR . $base . '_m.' . $extension;
    $image = Engine_Image::factory();
    $image->open($file)
      ->write($mainPath)
      ->destroy();

    // Resize image (profile)
    $profilePath = $path . DIRECTORY_SEPARATOR . $base . '_p.' . $extension;
    $image = Engine_Image::factory();
    $image->open($file)
      ->resize(200, 400)
      ->write($profilePath)
      ->destroy();

    // Resize image (normal)
    $normalPath = $path . DIRECTORY_SEPARATOR . $base . '_in.' . $extension;
    $image = Engine_Image::factory();
    $image->open($file)
      ->resize(100, 120)
      ->write($normalPath)
      ->destroy();

    // Resize image (icon)
    $squarePath = $path . DIRECTORY_SEPARATOR . $base . '_is.' . $extension;
    $image = Engine_Image::factory();
    $image->open($file);

    $size = min($image->height, $image->width);
    $x = ($image->width - $size) / 2;
    $y = ($image->height - $size) / 2;

    $image->resample($x, $y, $size, $size, 48, 48)
      ->write($squarePath)
      ->destroy();

    $db = Zend_Db_Table::getDefaultAdapter();
    $select = $db->select();
    $select->from('storage_files', array('file_id'))
      ->where('parent_id = ?' , $this->getIdentity())
      ->where('user_id = ?' , $this->getIdentity())
      ->where('parent_type = ?', $this->getType())
      ->where('type = ?', '')
      ->limit(1);

    $file = $db->fetchRow($select);
    $iMain = new Application_Model_Storage($file['file_id']);
    $iMain->fill($params);
    $iMain->bridge($mainPath);
    $iMain->save();

    $files = null;
    if ($file) {
      $profileQ = $db->select();
      $profileQ->from('storage_files', array('file_id', 'type'))
        ->where('parent_file_id = ?', $file['file_id'])
        ->limit(3);
      $files = $db->fetchAll($profileQ);
    }
    $cfiles = null;
    foreach ($files as $item) {
      $cfiles [$item['type']] = $item['file_id'];
    }

    $iProfile = new Application_Model_Storage($cfiles['thumb.profile']);
    $iProfile->fill($params);
    $iProfile->bridge($profilePath, 'thumb.profile');
    $iProfile->setParentFileId($iMain->getFileId());
    $iProfile->save();

    $iIconNormal = new Application_Model_Storage($cfiles['thumb.normal']);
    $iIconNormal->fill($params);
    $iIconNormal->bridge($normalPath, 'thumb.normal');
    $iIconNormal->setParentFileId($iMain->getFileId());
    $iIconNormal->save();

    $iSquare = new Application_Model_Storage($cfiles['thumb.icon']);
    $iSquare->fill($params);
    $iSquare->bridge($squarePath, 'thumb.icon');
    $iSquare->setParentFileId($iMain->getFileId());
    $iSquare->save();

    $this->setPhotoId($iMain->file_id);
    $this->save();
  }

  public function setPhotoId($id)
  {
    if ($id) {
      $this->photo_id = $id;
    }
  }

  public function getPhotoId()
  {
    return $this->photo_id;
  }
}

